from fastapi import APIRouter, Depends, HTTPException, status
from pydantic import BaseModel  # 导入Pydantic模型
from sqlalchemy.orm import Session
from ..database import get_db
from ..models.user import User
from ..auth.jwt_handler import create_access_token, get_current_user
from passlib.context import CryptContext
import uuid

router = APIRouter(
    prefix='/auth',  
    tags=['auth'],
)

# 密码加密上下文
pwd_context = CryptContext(schemes=['bcrypt'], deprecated='auto')

# 验证密码
def verify_password(plain_password, hashed_password):
    return pwd_context.verify(plain_password, hashed_password)

# 获取密码哈希
def get_password_hash(password):
    return pwd_context.hash(password)

# 定义登录请求模型
class LoginRequest(BaseModel):
    username: str
    password: str

# 用户注册
@router.post('/register')
def register_user(
    user_data: dict,  # 使用字典接收请求体，已兼容JSON格式
    db: Session = Depends(get_db)
):
    name = user_data.get('name')
    email = user_data.get('email')
    password = user_data.get('password')

    if not name or not email or not password:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail='所有字段都是必填的'
        )

    # 检查邮箱是否已存在
    existing_user = db.query(User).filter(User.email == email).first()
    if existing_user:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail='该邮箱已被注册'
        )

    # 加密密码
    hashed_password = get_password_hash(password)

    # 创建新用户
    user_id = str(uuid.uuid4())
    new_user = User(
        id=user_id,
        email=email,
        password=hashed_password,
        name=name  
    )
    db.add(new_user)
    db.commit()
    db.refresh(new_user)

    return {
        'message': '注册成功',
        'user': {
            'id': new_user.id,
            'name': new_user.name,
            'email': new_user.email,
        }
    }

# 用户登录（JWT令牌）- 改为JSON格式
@router.post('/token')
def login_for_access_token(
    login_data: LoginRequest,  # 使用Pydantic模型接收JSON请求体
    db: Session = Depends(get_db)
):
    user = db.query(User).filter(User.email == login_data.username).first()
    if not user or not verify_password(login_data.password, user.password):
        raise HTTPException(
            status_code=status.HTTP_401_UNAUTHORIZED,
            detail='Incorrect email or password',
            headers={'WWW-Authenticate': 'Bearer'},
        )
    access_token = create_access_token(data={'sub': user.email})
    return {'access_token': access_token, 'token_type': 'bearer'}

# 获取当前用户信息
@router.get('/me')
def get_me(current_user: User = Depends(get_current_user)):
    return {
        'id': current_user.id,
        'name': current_user.name,
        'email': current_user.email
    }